﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerDash : MonoBehaviour
{
    [Header("冲刺设置")]
    public float dashForce = 25f;
    public float dashCooldown = 1f;
    public SpriteRenderer playerSprite;
    public Color invincibleColor = new Color(1, 1, 1, 0.5f);
    [Header("无敌帧设置")]
    //public float invincibleDuration; 
    //public Collider2D[] playerColliders;

    private Rigidbody2D rb;
    private float lastDashTime = -1f;
    private Animator animator;
    

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        //playerColliders = GetComponentsInChildren<Collider2D>(); // 获取所有子物体碰撞体 
    }

    void Update()
    {
        Vector2 moveDirection = new Vector2(
            Input.GetAxisRaw("Horizontal"),
            Input.GetAxisRaw("Vertical")
        ).normalized;

        if (Input.GetKeyDown(KeyCode.Space) && moveDirection != Vector2.zero && Time.time - lastDashTime >= dashCooldown)
        {
            animator.SetBool("isDashing", true);
            rb.AddForce(moveDirection * dashForce, ForceMode2D.Impulse);
            lastDashTime = Time.time;

            // ▶️ 同时启动两个协程 
            StartCoroutine(DisableControlDuringDash(0.2f));
            //StartCoroutine(InvincibilityFrames(invincibleDuration));
        }
    }

    IEnumerator InvincibilityFrames(float duration)
    {
     //   SetCollidersEnabled(false);
        playerSprite.color = invincibleColor; // 半透明化
        yield return new WaitForSeconds(duration);
     //   SetCollidersEnabled(true);
        playerSprite.color = Color.white;  // 恢复颜色
    }
    
    //void SetCollidersEnabled(bool enabled)
    //{
    //    foreach (Collider2D col in playerColliders)
    //    {
    //        if (col == null) continue; // 空引用保护 
    //        col.enabled = enabled;
    //    }
    //}
    

    IEnumerator DisableControlDuringDash(float duration)
    {
        GetComponent<PlayerMovement>().enabled = false;
        yield return new WaitForSeconds(duration);
        GetComponent<PlayerMovement>().enabled = true;
        animator.SetBool("isDashing", false);
    }

}